#!/usr/bin/bash

if [ "${EUID:-$(id -u)}" -lt 1000 ]; then
  echo "Bazzite user setup ran as unsupported user. Exiting."
  exit 0
fi

IMAGE_INFO="/usr/share/ublue-os/image-info.json"
IMAGE_NAME=$(jq -r '."image-name"' < $IMAGE_INFO)
BASE_IMAGE_NAME=$(jq -r '."base-image-name"' < $IMAGE_INFO)
FEDORA_VERSION=$(jq -r '."fedora-version"' < $IMAGE_INFO)

SYS_ID="$(/usr/libexec/hwsupport/sysid)"
VEN_ID="$(cat /sys/devices/virtual/dmi/id/chassis_vendor)"

# INIT
BAZZITE_CONFIG_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/bazzite"
mkdir -p "$BAZZITE_CONFIG_DIR"

# SCRIPT VERSION
USER_SETUP_VER=46
USER_SETUP_VER_FILE="$BAZZITE_CONFIG_DIR/version"
USER_SETUP_FEDORA_VER_FILE="$BAZZITE_CONFIG_DIR/fedora_version"
USER_SETUP_IMAGE_VER_FILE=$BAZZITE_CONFIG_DIR/image_name""

if [[ -f "$HOME/.bazzite-configured" ]]; then
  mv -f "$HOME/.bazzite-configured" "$USER_SETUP_VER_FILE"
fi

if [[ -f "$HOME/.bazzite-configured-fedora-version" ]]; then
  mv -f "$HOME/.bazzite-configured-fedora-version" "$USER_SETUP_FEDORA_VER_FILE"
fi

# Run script if updated
if [[ -f $USER_SETUP_VER_FILE && -f $USER_SETUP_FEDORA_VER_FILE && -f $USER_SETUP_IMAGE_VER_FILE ]]; then
  USER_SETUP_VER_RAN=$(cat $USER_SETUP_VER_FILE)
  USER_SETUP_FEDORA_VER_RAN=$(cat $USER_SETUP_FEDORA_VER_FILE)
  USER_SETUP_IMAGE_VER_RAN=$(cat $USER_SETUP_IMAGE_VER_FILE)

  if [[ $USER_SETUP_VER = "$USER_SETUP_VER_RAN" && $FEDORA_VERSION = "$USER_SETUP_FEDORA_VER_RAN" && $BASE_IMAGE_NAME = "$USER_SETUP_IMAGE_VER_RAN" ]]; then
    echo "User setup v$USER_SETUP_VER has already run. Exiting..."
    exit 0
  fi
fi

# Handle privileged tasks
pkexec /usr/libexec/bazzite-privileged-user-setup "$USER"

PTYXIS_THEME_DIR="/etc/skel/.local/share/org.gnome.Ptyxis/palettes"
PTYXIS_DIR="$HOME/.local/share/org.gnome.Ptyxis/palettes"
mkdir -p "$PTYXIS_DIR"
if [[ ! -f "$PTYXIS_DIR/vapor.palette" ]]; then
  cp "$PTYXIS_THEME_DIR/vapor.palette" "$PTYXIS_DIR/vapor.palette"
fi
if [[ ! -f "$PTYXIS_DIR/vgui2.palette" ]]; then
  cp "$PTYXIS_THEME_DIR/vgui2.palette" "$PTYXIS_DIR/vgui2.palette"
fi

# Initialize Ptyxis config
# This is intentionally run on both images to ensure a user rebasing from Silverblue to Kinoite
# doesn't get their Ptyxis config wiped out.
if [[ ! -f "$BAZZITE_CONFIG_DIR/ptyxis-initialized" ]]; then
  echo 'Configuring Ptyxis'
  if [[ $BASE_IMAGE_NAME =~ "kinoite" ]]; then
    dconf load / < /usr/share/ublue-os/dconfs/desktop-kinoite/zz0-00-bazzite-desktop-kinoite-global
    dconf load / < /usr/share/ublue-os/dconfs/desktop-kinoite/00-bazzite-desktop-kinoite-ptyxis
  fi
  touch "$BAZZITE_CONFIG_DIR/ptyxis-initialized"
fi

# Fix Bazaar Shortcut for users that manually customized it
if [[ ! -f "$BAZZITE_CONFIG_DIR/bazaar-fix" ]]; then
  if [[ -f "$HOME/.local/share/applications/io.github.kolunmi.Bazaar.desktop" ]]; then
      if grep -qE '^Exec=.*(show|--auto-service)' "$HOME/.local/share/applications/io.github.kolunmi.Bazaar.desktop"; then
          rm -f "$HOME/.local/share/applications/io.github.kolunmi.Bazaar.desktop"
      fi
  fi
  touch "$BAZZITE_CONFIG_DIR/bazaar-fix"
fi

if [[ $BASE_IMAGE_NAME =~ "kinoite" ]]; then
  echo 'Running setup for Kinoite'

  if [[ $IMAGE_NAME =~ "deck" || $IMAGE_NAME =~ "ally" ]]; then
    echo 'Running setup for Kinoite on Steam Deck'
    if [[ ! -f "$HOME/Desktop/Return.desktop" ]]; then
      echo 'Re-creating return to gamemode shortcut'
      mkdir -p $HOME/Desktop/
      cp "/etc/skel/Desktop/Return.desktop" "$HOME/Desktop/Return.desktop"
    fi
  fi

  if [[ ":Framework:" =~ ":$VEN_ID:" ]]; then
    if [[ ! -f "$BAZZITE_CONFIG_DIR/framework-initialized" ]]; then
      CONFIG="$HOME/.config/plasma-org.kde.plasma.desktop-appletsrc"

      if [[ -f "$CONFIG" ]]; then
        # Find kickoff/application launcher applet sections
        APPLET_SECTIONS=$(grep -n '\[Containments\]\[[0-9]*\]\[Applets\]\[[0-9]*\]' "$CONFIG")

        # For each applet section, check if it's a launcher and update it
        while IFS=: read -r line_num line_content; do
          SECTION_NUM=$(echo "$line_content" | sed -E 's/\[Containments\]\[([0-9]+)\]\[Applets\]\[([0-9]+)\]/\1:\2/')
          CONT_NUM=$(echo "$SECTION_NUM" | cut -d: -f1)
          APP_NUM=$(echo "$SECTION_NUM" | cut -d: -f2)

          # Check if this is a launcher applet
          IS_LAUNCHER=$(grep -A 5 "\[Containments\]\[$CONT_NUM\]\[Applets\]\[$APP_NUM\]" "$CONFIG" | grep -i "kickoff\|launcher")

          if [[ -n "$IS_LAUNCHER" ]]; then
            echo "Found launcher applet in section $CONT_NUM:$APP_NUM, updating icon"
            kwriteconfig6 --file "$CONFIG" --group Containments --group $CONT_NUM --group Applets --group $APP_NUM --group Configuration --group General --key "icon" "framework"
          fi
        done <<<"$APPLET_SECTIONS"
      fi

      touch "$BAZZITE_CONFIG_DIR/framework-initialized"
    fi
  fi
else
  echo 'Running setup for Silverblue'

  if [[ ! -f "$BAZZITE_CONFIG_DIR/tiling-fix" ]]; then
    dconf write /org/gnome/mutter/edge-tiling true
    touch "$BAZZITE_CONFIG_DIR/tiling-fix"
  fi

  if /usr/libexec/hwsupport/valve-hardware; then
    if [[ ! -f "$BAZZITE_CONFIG_DIR/deck-initialized" ]]; then
      echo 'Setting Deck logo menu'
      dconf write /org/gnome/shell/extensions/Logo-menu/symbolic-icon true
      dconf write /org/gnome/shell/extensions/Logo-menu/menu-button-icon-image 2
      touch "$BAZZITE_CONFIG_DIR/deck-initialized"
    fi
  elif [[ ":83E1:" =~ ":$SYS_ID:" ]]; then
    if [[ ! -f "$BAZZITE_CONFIG_DIR/legion-initialized" ]]; then
      echo 'Setting Legion logo menu'
      dconf write /org/gnome/shell/extensions/Logo-menu/symbolic-icon true
      dconf write /org/gnome/shell/extensions/Logo-menu/menu-button-icon-image 5
      touch "$BAZZITE_CONFIG_DIR/legion-initialized"
    fi
  elif [[ ":ROG Ally RC71L:ROG Ally X RC72LA:" =~ ":$SYS_ID:" ]]; then
    if [[ ! -f "$BAZZITE_CONFIG_DIR/ally-initialized" ]]; then
      echo 'Setting Ally logo menu'
      dconf write /org/gnome/shell/extensions/Logo-menu/symbolic-icon true
      dconf write /org/gnome/shell/extensions/Logo-menu/menu-button-icon-image 6
      touch "$BAZZITE_CONFIG_DIR/ally-initialized"
    fi
  elif [[ ":Framework:" =~ ":$VEN_ID:" ]]; then
    if [[ ! -f "$BAZZITE_CONFIG_DIR/framework-initialized" ]]; then
      echo 'Setting Framework logo menu'
      dconf write /org/gnome/shell/extensions/Logo-menu/symbolic-icon true
      dconf write /org/gnome/shell/extensions/Logo-menu/menu-button-icon-image 4
      if [[ $SYS_ID == "Laptop ("* ]]; then
        echo 'Applying font fix for Framework 13'
        dconf write /org/gnome/desktop/interface/text-scaling-factor 1.25
      fi
      touch "$BAZZITE_CONFIG_DIR/framework-initialized"
    fi
  fi

  echo 'Setting up templates'
  TEMPLATES_DIR=$(/usr/bin/xdg-user-dir TEMPLATES || true)
  if [[ -z "$TEMPLATES_DIR" || "$TEMPLATES_DIR" == "$HOME" ]]; then
    # xdg-user-dir might return only $HOME, in that case, use fallback $HOME/Templates.
    echo "Using fallback '$HOME/Templates'"
    TEMPLATES_DIR="$HOME/Templates"
  fi
  mkdir -p "$TEMPLATES_DIR"

  if [[ ! -f "$TEMPLATES_DIR/vkBasalt.conf" && -f "/etc/vkBasalt.conf" ]]; then
    ln -s "/etc/vkBasalt.conf" "$TEMPLATES_DIR/vkBasalt.conf"
  fi
  if [[ ! -f "$TEMPLATES_DIR/dxvk.conf" && -f "/etc/dxvk-example.conf" ]]; then
    ln -s "/etc/dxvk-example.conf" "$TEMPLATES_DIR/dxvk.conf"
  fi
  if [[ ! -f "$TEMPLATES_DIR/MangoHud.conf" && -f "/usr/share/doc/mangohud/MangoHud.conf.example" ]]; then
    ln -s "/usr/share/doc/mangohud/MangoHud.conf.example" "$TEMPLATES_DIR/MangoHud.conf"
  fi

  if [[ $IMAGE_NAME =~ "deck" || $IMAGE_NAME =~ "ally" ]]; then
    echo 'Running setup for Silverblue on Steam Deck'

    echo 'Tweaking GNOME indexer'
    if [[ ! -f "$HOME/.steam/.trackerignore" ]]; then
      mkdir -p "$HOME/.steam"
      touch "$HOME/.steam/.trackerignore"
    fi
    if [[ ! -f "${XDG_DATA_HOME:-$HOME/.local/share}/Steam/.trackerignore" ]]; then
      mkdir -p "${XDG_DATA_HOME:-$HOME/.local/share}/Steam"
      touch "${XDG_DATA_HOME:-$HOME/.local/share}/Steam/.trackerignore"
    fi
  fi
fi

# Deck Build Setup
if [[ $IMAGE_NAME =~ "deck" || $IMAGE_NAME =~ "ally" ]]; then
  # SDGyroDSU Setup
  if /usr/libexec/hwsupport/valve-hardware; then
    systemctl --user enable --now sdgyrodsu.service
  else
    systemctl --user disable --now sdgyrodsu.service
  fi

  # Legion Rotation Fix
  AUTOSTART_FOLDER=${XDG_CONFIG_HOME:-$HOME/.config}

  # Remove old legion-only file
  if [[ -f "$AUTOSTART_FOLDER/autostart/bazzite-handle-legion-go-rotation.desktop" ]]; then
    rm -f "$AUTOSTART_FOLDER/autostart/bazzite-handle-legion-go-rotation.desktop"
  fi

  # Remove old rotation fix
  if [[ -f "$AUTOSTART_FOLDER/autostart/bazzite-rotation-fix.desktop" ]]; then
    rm -f "$AUTOSTART_FOLDER/autostart/bazzite-rotation-fix.desktop"
  fi
fi

# Audio Fix
# These handhelds use a custom DSP which requires the base speaker volume to be 100%
wp_audio_sinks() {
    wpctl status |
        awk 'BEGIN { A=0; S=0; }
            /^Audio/ { A=1; }
            /Sinks/ { S=1; }
            /Sources/ { S=0; }
            /Sink endpoints/ { S=0; }
            /^Video/ { A=0; }
            { if (A==1 && S==1 && / [[:digit:]]*\./) 
                 { print; } }' |
        sed 's/^.* \([[:digit:]]*\)\. \(.*\) \[.*$/\1\t\2/'   
}

if [[ ":83E1:ROG Ally RC71L:" =~ ":$SYS_ID:" ]]; then
  wpctl set-volume $(wp_audio_sinks | grep "17h/19h" | sed 's@^[^0-9]*\([0-9]\+\).*@\1@') 100% || true
fi

# Prevent future executions
echo "Writing state file"
echo $USER_SETUP_VER > $USER_SETUP_VER_FILE
echo $FEDORA_VERSION > $USER_SETUP_FEDORA_VER_FILE
echo $BASE_IMAGE_NAME > $USER_SETUP_IMAGE_VER_FILE
